package cn.jeeweb.modules.monitor.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ff.common.util.format.DateUtil;
import com.ff.common.util.format.JsonConvert;
import com.ff.common.util.validate.ValidatorUtil;

import cn.jeeweb.cache.MonitorTypeParaCache;
import cn.jeeweb.core.common.service.impl.CommonServiceImpl;
import cn.jeeweb.core.query.data.QueryRequest;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.utils.sms.data.SmsResult;
import cn.jeeweb.modules.constant.AlarmTypeEnum;
import cn.jeeweb.modules.monitor.entity.McMonitorOrg;
import cn.jeeweb.modules.monitor.entity.McProItemAlarm;
import cn.jeeweb.modules.monitor.mapper.McProItemAlarmMapper;
import cn.jeeweb.modules.monitor.service.IMcMonitorOrgService;
import cn.jeeweb.modules.monitor.service.IMcProItemAlarmService;
import cn.jeeweb.modules.sm.service.IProjectTypeService;
import cn.jeeweb.modules.sms.service.ISmsSendService;
import cn.jeeweb.modules.supervise.entity.McProItemMember;
import cn.jeeweb.modules.supervise.entity.McProItemMessage;
import cn.jeeweb.modules.supervise.entity.McProItemMonitorItem;
import cn.jeeweb.modules.supervise.entity.McProject;
import cn.jeeweb.modules.supervise.model.AlarmMsgModel;
import cn.jeeweb.modules.supervise.service.IMcProItemMemberService;
import cn.jeeweb.modules.supervise.service.IMcProItemMessageService;
import cn.jeeweb.modules.supervise.service.IMcProjectService;

/**   
 * @Title: 告警信息
 * @Description: 告警信息
 * @author Aether
 * @date 2017-12-02 12:58:21
 * @version V1.0   
 *
 */
@Transactional
@Service("mcProItemAlarmService")
public class McProItemAlarmServiceImpl  extends CommonServiceImpl<McProItemAlarmMapper,McProItemAlarm> implements  IMcProItemAlarmService {

  	protected Logger log = Logger.getLogger(getClass());
	@Autowired
	private ISmsSendService smsSendService;
	
	@Autowired
	private IMcProjectService projecService;
	
	@Autowired
	private IMcMonitorOrgService orgService;
 
	
	@Autowired
	private IMcProItemMemberService memberService;
	
	
	@Autowired
	private IMcProItemMessageService messageService;
	
	
	@Override
	public boolean insert(McProItemAlarm entity) {
		// TODO Auto-generated method stub
		

		return super.insert(entity);
	}
	@Autowired
	private MonitorTypeParaCache monitorTypeParaCache;
	public void sendMessage(McProItemMonitorItem item ,List<McProItemAlarm> alarmList)
	{
		if(ValidatorUtil.isEmpty(alarmList))
		{
			return;
		}
		try
		{
			
		String unit =	monitorTypeParaCache.get(item.getGroupTypeCode()).getUnit();
		McProItemAlarm entity = alarmList.get(0);
		String alarmMsg = "";
		String pointList = "";
 
		for(McProItemAlarm alarm :alarmList)
		{
			pointList += alarm.getMeasuringPointCode() + ",";
			alarmMsg +=  alarm.getMeasuringPointCode() +"(";
			alarmMsg += String.format("%.1f", entity.getSumValue()) + unit;
			
			if(!ValidatorUtil.isEmpty(item.getRateChangeControlValue()) && (AlarmTypeEnum.OVERLOAD.getValue().equals(entity.getAlarmTypeId())) )
 			{
				alarmMsg += "、"+String.format("%.1f", entity.getChangeRate()) + unit+"/d";
   			}
			if(!ValidatorUtil.isEmpty(item.getRateChangeAlarmValue()) && (AlarmTypeEnum.ALARM.getValue().equals(entity.getAlarmTypeId())) )
 			{
				alarmMsg += "、"+String.format("%.1f", entity.getChangeRate()) + unit+"/d";
   			}
		    alarmMsg += "),";
			
     	}
 		if (AlarmTypeEnum.OVERLOAD.getValue().equals(entity.getAlarmTypeId()))
 		{
 			alarmMsg += "超出设计控制值(";
 			alarmMsg += item.getTotalControlValue() + ",";
 			if(!ValidatorUtil.isEmpty(item.getRateChangeControlValue()))
 			{
 	 			alarmMsg += item.getRateChangeControlValue();
  			}
 			alarmMsg += ")";
 		}
 		else if (AlarmTypeEnum.ALARM.getValue().equals(entity.getAlarmTypeId()))
  		{
 			alarmMsg += "超出设计报警值(";
 			alarmMsg += item.getTotalAlarmValue() +",";
 			if(!ValidatorUtil.isEmpty(item.getRateChangeAlarmValue()))
 			{
 	 			alarmMsg += item.getRateChangeAlarmValue();
  			}
 			alarmMsg += ")";
 		}
 		else if (AlarmTypeEnum.WARN.getValue().equals(entity.getAlarmTypeId()))
  		{
 			alarmMsg += "超出设计预警值(";
 			alarmMsg += item.getYellowWarningValue();
 			alarmMsg += ")";
 		}
		
		McProject project =	projecService.selectById(entity.getProjectId());
		
		McMonitorOrg org = orgService.selectById(project.getMonitorId());
		
		Queryable queryable = QueryRequest.newQueryable();
		queryable.addCondition("projectId", entity.getProjectId());
		List<McProItemMember> memList = memberService.listWithNoPage(queryable);
		
		String phone = "";
		String name = "";
		String ids = "";
		for(McProItemMember mem : memList)
		{
			if(null != mem.getMsgPerm())
			{
				
				if(  (AlarmTypeEnum.WARN.getValue().equals(entity.getAlarmTypeId()) && mem.getMsgPerm().contains("warn"))
				  || (AlarmTypeEnum.ALARM.getValue().equals(entity.getAlarmTypeId()) && mem.getMsgPerm().contains("alarm"))
				  || (AlarmTypeEnum.OVERLOAD.getValue().equals(entity.getAlarmTypeId()) && mem.getMsgPerm().contains("control")))
				{
					phone += mem.getPhone() + ",";
					ids += mem.getUserId() + ",";
					name += mem.getUsername() + ",";
				}
			}
		}
		AlarmMsgModel model = new AlarmMsgModel();
		model.setMonitorUnit(org.getName());
		model.setProjectName(entity.getProjectName());
		model.setMonitorItemName(entity.getMonitorItemName());
 		model.setTime(DateUtil.DateToString(DateUtil.getCurrentDate()));
 		model.setAlarmMsg(alarmMsg);
 		McProItemMember mem = memberService.selectById(project.getPersonInCharge());
 		model.setProjectMember(project.getPersonInChargeName());
 		if(null != mem)
 		{
 	 		model.setProjectMember(project.getPersonInChargeName()+"("+ mem.getPhone() + ")");
  		}
		
		model.setWebsite("www.guokanyun.net");
	
		McProItemMessage message = new McProItemMessage();
		message.setMonitorId(item.getId());
		
		message.setProjectId(project.getId());
		message.setProjectName(project.getName());
		message.setMonitorItemId(item.getId());
		message.setMonitorItemName(item.getMonitorItemName());
		message.setPonitList(pointList);
		message.setUserId(ids);
		message.setUserName(name);
		message.setPhone(phone);
		message.setStatus("未读");
		
		message.setType("短信");
		String content = "%s提醒您，%s项目%s测点于%s报警：%s。详情请登录网站%s或联系项目负责人%s。";
		content = String.format(content, model.getMonitorUnit(),model.getProjectName(),model.getMonitorItemName(),model.getTime(),model.getAlarmMsg(),model.getWebsite(),model.getProjectMember());
		
		message.setContent(content);
		
		SmsResult smsResult = smsSendService.sendSyncSmsByCode(phone, "129604", model.getMonitorUnit(),model.getProjectName(),model.getMonitorItemName(),model.getTime(),model.getAlarmMsg(),model.getWebsite(),model.getProjectMember());
		message.setResult(smsResult.getMsg());
		messageService.insert(message);
 		    
		}
		catch(Exception e)
		{
			log.error("error",e);
		}
	}
	
}
